package com.beordie.service.impl;

import com.beordie.dao.IMiddleMenuDao;
import com.beordie.dao.IRoleDao;
import com.beordie.dao.impl.MiddleMenuDaoImpl;
import com.beordie.dao.impl.RoleDaoImpl;
import com.beordie.model.Role;
import com.beordie.model.Users;
import com.beordie.service.IRoleService;

import java.util.List;

/**
 * @Classname RoleServiceImpl
 * @Description TODO
 * @Date 2021/6/16 22:45
 * @Created 30500
 */
public class RoleServiceImpl implements IRoleService {
    private IRoleDao roleDao = new RoleDaoImpl();
    private IMiddleMenuDao middleMenuDao = new MiddleMenuDaoImpl();

    @Override
    public int getAllTotal() {
        return roleDao.getAllTotal();
    }

    @Override
    public List<Role> getByLimit(int index, int pageSize) {
        return roleDao.getByLimit(index, pageSize);
    }

    @Override
    public List<Role> getAll() {
        return roleDao.getAll();
    }

    @Override
    public int add(String roleName, String roleState, String[] menuID) {
        // 拿到新插入的角色的 ID
        Role role = new Role();
        role.setRoleName(roleName);
        role.setRoleState(Integer.parseInt(roleState));
        int roleID = roleDao.add(role);
        if (roleID == 0)
            return 0;
        // 转换数据为数据库支持的格式
        int[] menuId = new int[menuID.length];
        for (int i = 0; i < menuId.length; i++) {
            menuId[i] = Integer.parseInt(menuID[i]);
        }

        // 拿到最终的返回结果
        int[] result = middleMenuDao.add(roleID, menuId);
        if (result != null && result.length > 0)
            return 1;
        else
            return 0;
    }

    @Override
    public int delete(int roleId) {
        // 先删除中间表的数据
        int resultM = middleMenuDao.delete(roleId);

        // 删除角色表的数据
        int resultR = roleDao.delete(roleId);

        return 1;
    }

    @Override
    public Role getById(int roleId) {
        return roleDao.getById(roleId);
    }

    @Override
    public int update(String roleId, String roleName, String roleState, String[] menuID) {
        Role role = new Role();
        role.setRoleId(Integer.parseInt(roleId));
        role.setRoleName(roleName);
        role.setRoleState(Integer.parseInt(roleState));
        // 转换数据为数据库支持的格式
        int[] menuId = new int[menuID.length];
        for (int i = 0; i < menuId.length; i++) {
            menuId[i] = Integer.parseInt(menuID[i]);
        }

        // 执行更新操作
        roleDao.update(role);
        middleMenuDao.delete(role.getRoleId());
        middleMenuDao.add(role.getRoleId(), menuId);
        return 1;
    }

}
